<template>
    <div class="index">
        <!--搜索header-->
        <div class="header_search" style="text-align: center;position:fixed;top:0;z-index:222">
            <div class="search_ipt">
                <img src="../../assets/img/search_icon.png" alt="" @click="search()">
                <input id="search" type="search" class="mui-input-clear" placeholder="搜索商品、品类" v-model="keyWord" @keyup="show($event)">
            </div>
        </div>
        <!--轮播-->
        <div class="swiper-container">
            <div class="swiper-wrapper">
                <div class="swiper-slide" v-for="item in banner">
                	<router-link :to="{path:item.url,query:{class_id:getClassId(item.url),taoqinggouName:'/brand'}}" v-if="item.url=='all'||item.url=='meizhuang'||item.url=='muying'||item.url=='jiadian'||item.url=='jiafang'">
                		<img :src="imageDomain+item.imageUrl" alt="">
                	</router-link>
                	<div  @click="goDetail(item.url)" v-else>
                		<img  :src="imageDomain+item.imageUrl" alt="">
                	</div>
                </div>
            </div>
            <!-- 如果需要分页器 -->
            <div class="swiper-pagination"></div>
        </div>
        <!--menu-->
        <ul class="menu horizontal-list clear">
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:69}}"><img
                        src="../../assets/img/index/menu1.png" alt="">母婴玩具
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:70}}"><img
                        src="../../assets/img/index/menu2.png" alt="">潮流服饰
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:71}}"><img
                        src="../../assets/img/index/menu3.png" alt="">美妆个护
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:72}}"><img
                        src="../../assets/img/index/menu4.png" alt="">食品饮料
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:73}}"><img
                        src="../../assets/img/index/menu5.png" alt="">数码科技
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:74}}"><img
                        src="../../assets/img/index/menu6.png" alt="">珠宝饰品
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/item_classify',query:{fcategory:75}}"><img
                        src="../../assets/img/index/menu7.png" alt="">家纺家饰
                </router-link>
            </li>
            <li>
                <router-link :to="{path:'/classify'}"><img src="../../assets/img/index/menu_more.png" alt="">更多
                </router-link>
            </li>
        </ul>
        
        <!--秒杀-->
        <div class="seckill">
            <div class="title">
               <router-link :to="{path:'/miaosha'}">
	               	<span class="fr words">精选秒杀好货<img src="../../assets/img/index/redarr.png" alt="" /></span>
	            	<img class="clock" src="../../assets/img/index/clock.png"/><img class="miaosha" src="../../assets/img/index/yabei.png"/>
	            	<span class="time">{{getSession}}点场</span><span class="time-detail"><span class="shape">{{date.hour}}</span>&nbsp;:&nbsp;<span  class="shape">{{date.minute}}</span>&nbsp;:&nbsp;<span class="shape">{{date.second}}</span></span>
               </router-link>
              </div>
               <div class="allSort mt mb f14" style="overflow-y: visible;min-height:160px">
                <div class="sortMenu clearfix content" style="overflow-y: visible;min-height:160px">
                    <ul class="sortMenu-ul goods-lists" style="overflow: visible;min-height:160px;font-size:0;" >
                    <li class="cell goods-item" v-for="item in getGoods" @click="goDetail(item.new_url) " style="min-height:160px;margin:0;padding:0;">
                        <img :src="'http:'+item.thumb"/>
            			<div class="text-center f16 cff4" style="height:20px;line-height:20px;">￥{{item.price}}</div>
            			<div class="text-center text-decoration c999 f14" style="height:20px;line-height:20px;">￥{{Math.floor(item.price*1.5+2)}}</div>
                    </li>
                    </ul>
                </div>
            </div>
        </div>
        <!--猜你喜欢-->
        <mt-loadmore :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" @bottom-status-change="handleTopChange"
                     ref="loadmore">
            <ul class="guess vertical-list">
                <li class="guess_header">
                    <img src="../../assets/img/index/guess_icon.png" alt="">猜你喜欢
                </li>
                <li class="item_goods" v-for="product in products">
                    <router-link :to="{path:'/detail',query:{productId:product.productId}}">
                        <img class="goods_img" :src="imageDomain+product.image" :alt="product.productName">
                        <div class="goods_info">
                            <p class="goods_desc"><span class="cff4" v-if="product.shopId==21">【自营】</span>{{product.productName}}</p>
                            <p class="price"> ￥{{product.price}}</p>
                        </div>
                    </router-link>
                    <!--<img class="add_cart" src="../../assets/img/index/add.png"/>-->
                </li>
            </ul>
        </mt-loadmore>
    </div>
</template>

<style>
    @import url("./index.css");
    @import url('../../assets/css/swiper.css');
</style>
<script>
    import Layer from '../../assets/js/MessageBox'
    import API from '../../assets/js/API'

    export default {
        data() {
            return {
                topStatus: '',
                imageDomain: API.imageDomain,
                products: [],
                allLoaded: false,
                productQuery: {
                    currentPage: 1,
                    homeFlag: "1"
                },
                keyWord: '',
                banner: '',
                versionInfo: {
                    type: "1",
                    version: API.currentVersion
                },
                checkResult: {},
                date:{
                    sessions:[0,8,10,12,14,16,18,20,22],
                    hour:0,
                    minute:0,
                    second:0,
                    goodsLists:[],
                    products:[],
                }
            }
        },
         beforeRouteEnter (to, from, next) {
           if(from.path!='/detail'){
                window.scrollTo(0,0);
           }
           next()
        },
        created() {
            let checkUrl = API.serviceDomain + API.checkVersion;//进行新版本的检测
            let isIos = this.isIOS();
            if (isIos) {
                this.versionInfo.type = "2";
            }
            this.$http.post(checkUrl, this.versionInfo).then(
                (res) => {
                    if (res.body.status == '000000') {
                        this.checkResult = res.body.data;
                        console.log(res.body.data)
                        if (this.checkResult.upgrade == "1") {
                            if (this.versionInfo.type == "1") {
                                if (this.checkResult.must == "1") {
                                    this.mustDownload();
                                } else {
                                    this.chooseDownload();
                                }
                            }else{
                                if (this.checkResult.must == "1") {
                                    this.mustUpdate(this.checkResult.fileUrl);
                                } else {
                                    this.chooseUpdate(this.checkResult.fileUrl);
                                }
                            }
                        }else{
                            this.loadData();//新版本检测通过后进行数据的加载
                        }
                    } else {
                        Layer.showMsg(res.body.message);
                    }
                },
                (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
            );
        },
        mounted() {
            
        },
        computed:{
             getSession(){
                 if(this.date.hour>=8){
                    let index=Math.floor(this.date.hour/2-3)
                    return this.date.sessions[index]
                 }else{
                     return 0;
                 }
               
            },
            getGoods(){
                 if(this.date.hour>=8){
                    let index=Math.floor(this.date.hour/2-3)
                    return this.date.goodsLists[index]
                 }else{
                     return this.date.goodsLists[0]
                 }
            },

        },
       methods:{
              goDetail(new_url) {
                if(new_url){
                     var w=plus.webview.create( new_url,'taobao');
                      w.show();
                //     plus.runtime.openURL(new_url,function(){
                //         plus.runtime.openURL(new_url);
                //    },'com.taobao.taobao');
                }
                   
            },
             miaoShaGoods(){
                let url=API.taotejia+'/rank';
                let form=new FormData()
                  this.$http.post(url,form,
                  {
                       headers: {'Content-Type': 'application/x-www-form-urlencoded,multipart/form-data'}
                  }
                  ).then(
                (res) => {
                    if (res.body.code==1) {
                         this.date.products= res.body.data.result;
                             let all=this.date.sessions.length;
                            let num=Math.floor(res.body.data.result.length/ all)
                            for(let i=0;i<all;i++){
                                this.date.products=[];
                                let start=i*num;
                                let end=start+num
                                for(let j=start;j<end;j++){
                                    this.date.products.push(res.body.data.result[j])
                                 } 
                                 this.date.goodsLists.push(this.shuffle(this.date.products))
                            }
                           
                        
                    } else {
                        Layer.showMsg("获取列表失败！");
                    }
                },
                (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
            )
            },
             shuffle(a) {
                var b = [];
                while (a.length > 0) {
                    var index = parseInt(Math.random() * (a.length - 1));
                    b.push(a[index]);
                    a.splice(index, 1);
                }
                return b;
            },
            getDate(){
                let vm=this;
                setInterval(function(){
                    let new_Date=new Date();
                     vm.date.hour=new_Date.getHours();
                      vm.date.minute=new_Date.getMinutes();
                     vm.date.second=new_Date.getSeconds()
                     if(vm.date.minute<10){
                         vm.date.minute='0'+vm.date.minute
                     }
                     if( vm.date.second<10){
                          vm.date.second='0'+ vm.date.second
                     }
                     if(vm.date.hour<10){
                         vm.date.hour='0'+ vm.date.hour
                     }
                },1000)
              
            },
            getClassId(url){
                if(url=='meizhuang'){
                    return 5;
                }else if(url=='muying'){
                    return 4;
                }else if(url=='jiadian'){
                    return 12
                }else if(url=='jiafang'){
                    return 6
                }else{

                }
            },
            goBack() {
                this.$router.goBack()
            },
            addRecord() {
                let url = API.serviceDomain + API.productArray;
                this.nextIndex();
                this.$http.post(url, this.productQuery).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            if (res.body.data == null) {
                                this.allLoaded = true;// 若数据已全部获取完毕
                            } else {
                                this.products = this.products.concat(res.body.data);
                            }
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )
            },
            loadTop() {
                this.resetIndex();
                this.$refs.loadmore.onTopLoaded();
            },
            loadBottom() {
                // 加载更多数据
                this.addRecord();
                this.$refs.loadmore.onBottomLoaded();
            },
            handleTopChange(status) {
                this.topStatus = status;
            },
            nextIndex() {
                this.productQuery.currentPage = this.productQuery.currentPage + 1;
            },
            resetIndex() {
                this.productQuery.currentPage = 1;
            },
            search() {
                this.$router.push({path: '/item_classify', query: {'keyWord': this.keyWord}})
            },
            mustUpdate(url){
                layer.confirm('当前有最新版本,确定下载？', {
                    btn: ['必须下载哦...'] //按钮
                }, function () {
                    plus.runtime.openURL(url);
                }, function () {
                    return false;
                });
            },
            mustDownload() {
                 layer.confirm('当前有最新版本,确定下载？', {
                    btn: ['必须下载哦...'] //按钮
                }, function () {
                    var url = API.serviceDomain + "/app/android/download";
                    var encodeUrl = encodeURI(url);//文件的具体地址，具体到文件名称
                    var dtask = plus.downloader.createDownload(encodeUrl, {method: "GET"});//新建下载任务
                    var w = plus.nativeUI.showWaiting("开始下载...");
                    dtask.addEventListener("statechanged", function (task, status) {
                        switch (task.state) {
                            case 3:	// 已接收到数据
                                if (w) {
                                    w.setTitle("数据下载中....." + task.downloadedSize);
                                }
                                break;
                            case 4:	// 下载完成
                                if (status == 200) {
                                    if (w) {
                                        w.close();
                                    }
                                    plus.runtime.openFile(task.filename, {}, function (e) {
                                        QxMobile.Alert("无法打开此文件：" + e.emssage);
                                    });
                                } else {
                                    Alert("下载失败：" + status);
                                    plus.nativeUI.closeWaiting();
                                }
                                break;
                        }
                    });
                    dtask.start();
                }, function () {
                    return false;
                });
               
            },
            chooseUpdate(url){
                let _this = this;
                layer.confirm('当前有最新版本,确定下载？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    plus.runtime.openURL(url);
                }, function () {
                    _this.loadData();
                });
            },
            chooseDownload() {
                let _this = this;
                layer.confirm('当前有最新版本,确定下载？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    var url = API.serviceDomain + "/app/android/download";
                    var encodeUrl = encodeURI(url);//文件的具体地址，具体到文件名称
                    var dtask = plus.downloader.createDownload(encodeUrl, {method: "GET"});//新建下载任务
                    var w = plus.nativeUI.showWaiting("开始下载...");
                    dtask.addEventListener("statechanged", function (task, status) {
                        switch (task.state) {
                            case 3:	// 已接收到数据
                                if (w) {
                                    w.setTitle("数据下载中....." + task.downloadedSize);
                                }
                                break;
                            case 4:	// 下载完成
                                if (status == 200) {
                                    if (w) {
                                        w.close();
                                    }
                                    plus.runtime.openFile(task.filename, {}, function (e) {
                                        QxMobile.Alert("无法打开此文件：" + e.emssage);
                                    });
                                } else {
                                    Alert("下载失败：" + status);
                                    plus.nativeUI.closeWaiting();
                                }
                                break;
                        }
                    });
                    dtask.start();
                }, function () {
                    _this.loadData();
                });
            },
            loadData(){
                 this.getDate();
                   this.miaoShaGoods();
                let url = API.serviceDomain + API.productArray;      
                this.$http.post(url, this.productQuery)
                .then(
                    (res) => {
                        if (res.body.status == '000000') {
                            this.products = res.body.data;
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )
                this.$http.get(API.serviceDomain + API.indexBanner).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            this.banner = res.body.data;
                            setTimeout(function () {
                                let mySwiper = new Swiper('.swiper-container', {
                                    autoplay: 2500,//可选选项，自动滑动
                                    autoplayDisableOnInteraction: false,
                                    loop: true,
                                    pagination: '.swiper-pagination',
                                });
                            }, 100);

                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                );
            },
            isIOS(){
                let u = navigator.userAgent;
                let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
                let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                return isiOS
            },
            show(ev) {
                if(ev.keyCode==13){
                    this.search();
                }
            }
        }
    }
</script>
